<template>
    <div class="page-wrap">
        <sys-set @success="sysSetChange" v-if="!$store.getters.userInfo.employeeDTO.isShowSideTree" />
        <a-divider class="full-divider-h" v-if="!$store.getters.userInfo.employeeDTO.isShowSideTree" />
        <flexbox justify="space-between" align="flex-start" class="table-toolbar-wrap">
            <flexbox>
                <filter-form @search="handleSearch" v-show="!selectedRowKeys.length" />
                <flexbox align="center" class="btn-group-wrap margin-l-16" v-show="selectedRowKeys.length">
                    <span class="margin-r-16">
                        已选中<a>{{ selectedRowKeys.length }}</a> 项
                    </span>
                    <a-button type="primary" :disabled="selectedRowKeys.length < 2" @click="handleMergeRequire"> 合并需求 </a-button>
                    <a-button type="primary" @click="exportFile"> 导出需求单 </a-button>
                </flexbox>
            </flexbox>
            <flexbox>
                <a-button type="primary" :disabled="!list.length" class="margin-r-16" @click="exportAllFile(0)">导出</a-button>
                <a-tooltip title="表格列配置">
                    <column-setting :columns="settingColumns" @setColumns="setColumns" />
                </a-tooltip>
            </flexbox>
        </flexbox>
        <custom-table
            autoResize
            rowKey="id"
            size="small"
            :loading="loading"
            :columns="tableColumns"
            :data-source="list"
            :pagination="paginationConfig"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :expandIcon="handleExpandIcon"
            @change="handleTableChange"
            @expand="onExpandChange"
        >
            <template #customSystemTitle>
                <span style="margin-left: 20px">所属产品</span>
            </template>
            <template #systemName="{ record }">
                <router-link
                    :to="{ path: '/productAnalysis/productDetail', query: { id: record.requestSystem } }"
                    :style="{ marginLeft: (+record.stage >= 4 && record.isSplit === '是') || record.relateRequest > 0 ? 0 : '20px' }"
                    v-if="record.systemName && !record.systemName.includes(',')"
                >
                    {{ record.systemName }}
                </router-link>
                <span :style="{ marginLeft: (+record.stage >= 4 && record.isSplit === '是') || record.relateRequest > 0 ? 0 : '20px' }" v-else>{{
                    record.systemName
                }}</span>
            </template>

            <template #pmpLabels="{ record }">
                <a-tag color="blue" style="max-width: 100%; margin-bottom: 2px" v-fitText v-for="item of record.pmpLabels" :key="item.id">
                    {{ item.name }}
                </a-tag>
            </template>
            <template #requestName="{ record }">
                <a @click.stop="showDetail(record.id)">
                    {{ record.requestName }}
                </a>
                <a-tag v-if="record.requireChange === 0" color="orange" class="margin-l-8">需求变更</a-tag>
            </template>
            <template #requestType="{ record }"> {{ $filters.valToNameFilter('requestType', record.requestType) }} </template>
            <template #level="{ record }">
                <h-level :level="record.level" v-if="record.level" />
            </template>
            <template #stage="{ record }"> {{ $filters.valToNameFilter('stage', record.stage) }} </template>
            <template #status="{ record }">
                <h-status-badge :status="record.status" />
            </template>
            <template #initiatorTime="{ record }"> {{ $filters.dateFilter(record.initiatorTime) }} </template>
            <template #estimateTime="{ record }"> {{ $filters.dateFilter(record.estimateTime) }} </template>
            <template #requestSystem="{ record }"> {{ $filters.valToNameFilter('fromSystem', record.requestSystem) }} </template>
            <template #action="{ record }">
                <TableAction :record="record" @actionEvent="handleMenuEvent" />
            </template>
        </custom-table>
        <merge-require ref="mergeRequireRef" :list="selectedRows" @success="getList" />
        <relative-change-table ref="relativeChangeTableRef" />
    </div>
</template>

<script lang="ts">
import FilterForm from './components/filterForm.vue';
import {
    useTableData,
    useTableLoading,
    usePagination,
    useTableColumns,
    useTableExpand,
    useTableRowSelect,
    useTableFormSearch,
    useTableAction,
    useTableToolbar
} from '@/components/Table/hooks/index';
import { useMountedAndActivated } from '@/hooks/common/useMountedAndActivated';
import api from '@/api';
import store from '@/store';
import { useSystemSet } from '@/components/SysSet/hooks/useSystemSet';
import { HLevel, HStatusBadge, CustomTable, ColumnSetting, SysSet } from '@/components';
import RelativeChangeTable from '@/components/Content/RelativeChangeTable.vue';
import TableAction from './components/tableAction.vue';
import MergeRequire from './components/mergeRequire.vue';
import { downByBlob } from '@/utils/file/downFile';
import { defineComponent, ref, unref } from 'vue';

export default defineComponent({
    name: 'taskRequirements',
    components: {
        FilterForm,
        MergeRequire,
        HLevel,
        HStatusBadge,
        RelativeChangeTable,
        TableAction,
        CustomTable,
        ColumnSetting,
        SysSet
    },
    setup() {
        const relativeChangeTableRef = ref();
        const mergeRequireRef = ref();

        const { loading, setLoading } = useTableLoading();
        const { paginationConfig, setPaginationConfig } = usePagination();
        const { columns: tableColumns, setColumns, settingColumns } = useTableColumns('taskRequirements');
        const { list, searchQuery, getList, setList, handleTableChange, setSearchQuery } = useTableData(
            setLoading,
            paginationConfig,
            setPaginationConfig,
            'taskRequirements'
        );
        const { handleExpandIcon, onExpandChange } = useTableExpand('sonRequestInfos', list, setList);
        const { selectedRowKeys, selectedRows, onSelectChange } = useTableRowSelect();
        const { handleSearch } = useTableFormSearch(setPaginationConfig, setSearchQuery, getList);
        const { showDetail, handleDelete, showRequireChangeDetail, handleChangeRequire } = useTableAction(
            'taskRequirements',
            getList,
            relativeChangeTableRef
        );
        const { exportAllFile } = useTableToolbar(searchQuery, paginationConfig);
        const { system, sysSetChange } = useSystemSet(setPaginationConfig, setSearchQuery, getList);
        // 合并需求
        const handleMergeRequire = () => {
            mergeRequireRef.value.open();
        };
        //导出需求单
        const exportFile = (): void => {
            unref(selectedRows).forEach(async ({ id, requestName }) => {
                const res = await api.fileModel.exportFile({ id }, { responseType: 'blob' });
                res && downByBlob(res, requestName + '.doc');
            });
        };
        // 操作回调
        const handleMenuEvent = ({ type, record }) => {
            const { id, requestName } = record;
            switch (type) {
                case 'detail':
                    showDetail(id);
                    return;
                case 'showChange':
                    showRequireChangeDetail(id, 0);
                    return;
                case 'change':
                    handleChangeRequire(id);
                    return;
                case 'delete':
                    handleDelete(id, requestName);
                    return;
            }
        };
        setSearchQuery({
            selectType: 'pool',
            status: null,
            stage: null,
            // admin: store.getters.userInfo.roles.includes('admin') ? 1 : 0, // 判断角色是否含有admin
            admin: store.getters.userInfo.roles.some((item) => ['admin', '观察者', '领导', '产品管理委员会'].includes(item)) ? 1 : 0
        });
        useMountedAndActivated(getList, false);
        return {
            mergeRequireRef,
            system,
            handleMergeRequire,
            exportFile,
            exportAllFile,
            relativeChangeTableRef,
            handleMenuEvent,
            list,
            tableColumns,
            settingColumns,
            loading,
            selectedRowKeys,
            selectedRows,
            handleExpandIcon,
            paginationConfig,
            handleTableChange,
            onExpandChange,
            onSelectChange,
            showDetail,
            handleSearch,
            getList,
            setColumns,
            sysSetChange
        };
    }
});
</script>
<style scoped lang="less">
.page-wrap {
    min-height: 100%;
    padding: 8px 24px 12px 24px;
    background: #fff;
    .table-toolbar-wrap {
        margin-bottom: 16px;
        .ant-btn + .ant-btn {
            margin-left: 8px;
        }
    }
    .table-toolbar-wrap {
        margin-bottom: 16px;
        .ant-btn + .ant-btn {
            margin-left: 8px;
        }
    }
    .table-title {
        font-size: 16px;
        font-weight: bold;
    }
    // ::v-deep(tr.ant-table-expanded-row-level-1) {
    //     display: none !important;
    // }
}
</style>